#include <iostream>
#include <sstream>
#include <algorithm>
#include "execution/expression_evaluator.h"
#include "execution/catalog.h"

// Find the position of the top-level AND/OR operator
std::pair<std::string, size_t> findTopLevelLogicalOperator(const std::string& expr) {
    int parenCount = 0;
    size_t pos = 0;
    
    // 寻找最外层的AND运算符
    pos = 0;
    while ((pos = expr.find(" AND ", pos)) != std::string::npos) {
        // 检查该位置是否在括号内
        int tempParenCount = 0;
        bool inQuotes = false;
        char quoteChar = 0;
        
        for (size_t i = 0; i < pos; ++i) {
            if (expr[i] == '"' || expr[i] == '\'') {
                if (!inQuotes) {
                    inQuotes = true;
                    quoteChar = expr[i];
                } else if (expr[i] == quoteChar) {
                    inQuotes = false;
                }
            }
            if (!inQuotes) {
                if (expr[i] == '(') tempParenCount++;
                if (expr[i] == ')') tempParenCount--;
            }
        }
        
        if (tempParenCount == 0) {
            return {"AND", pos};
        }
        
        pos += 5; // 跳过 " AND "
    }
    
    // 寻找最外层的OR运算符
    pos = 0;
    while ((pos = expr.find(" OR ", pos)) != std::string::npos) {
        // 检查该位置是否在括号内
        int tempParenCount = 0;
        bool inQuotes = false;
        char quoteChar = 0;
        
        for (size_t i = 0; i < pos; ++i) {
            if (expr[i] == '"' || expr[i] == '\'') {
                if (!inQuotes) {
                    inQuotes = true;
                    quoteChar = expr[i];
                } else if (expr[i] == quoteChar) {
                    inQuotes = false;
                }
            }
            if (!inQuotes) {
                if (expr[i] == '(') tempParenCount++;
                if (expr[i] == ')') tempParenCount--;
            }
        }
        
        if (tempParenCount == 0) {
            return {"OR", pos};
        }
        
        pos += 4; // 跳过 " OR "
    }
    
    return {"", std::string::npos};
}

// Evaluate simple expression (expression without AND/OR)
bool evaluateSimpleExpression(const std::string& filter, const std::vector<std::string>& record, const TableInfo& tableInfo, int line = 0, int column = 0) {
    // 去除首尾空格
    std::string trimmedFilter = filter;
    size_t start = trimmedFilter.find_first_not_of(" ");
    size_t end = trimmedFilter.find_last_not_of(" ");
    if (start != std::string::npos && end != std::string::npos) {
        trimmedFilter = trimmedFilter.substr(start, end - start + 1);
    }
    
    // 处理带括号的情况
    if (!trimmedFilter.empty() && trimmedFilter.front() == '(' && trimmedFilter.back() == ')') {
        trimmedFilter = trimmedFilter.substr(1, trimmedFilter.size() - 2);
        // 再次去除空格
        start = trimmedFilter.find_first_not_of(" ");
        end = trimmedFilter.find_last_not_of(" ");
        if (start != std::string::npos && end != std::string::npos) {
            trimmedFilter = trimmedFilter.substr(start, end - start + 1);
        }
    }
    
    std::istringstream iss(trimmedFilter);
    std::string left, op, right;
    
    if (!(iss >> left)) {
        if (line > 0 && column > 0) {
            std::cerr << "Error at line " << line << ", column " << column << ": Invalid expression format: " << filter << std::endl;
        } else {
            std::cerr << "Error: Invalid expression format: " << filter << std::endl;
        }
        return false;
    }
    
    if (!(iss >> op)) {
        if (line > 0 && column > 0) {
            std::cerr << "Error at line " << line << ", column " << column << ": Missing operator in expression: " << filter << std::endl;
        } else {
            std::cerr << "Error: Missing operator in expression: " << filter << std::endl;
        }
        return false;
    }
    
    std::string remaining;
    std::getline(iss, remaining);
    remaining = remaining.substr(remaining.find_first_not_of(" "));
    
    if (!remaining.empty() && (remaining.front() == '"' || remaining.front() == '\'')) {
        size_t lastQuotePos = remaining.find_last_of("'\"");
        if (lastQuotePos != std::string::npos) {
            right = remaining.substr(0, lastQuotePos + 1);
        } else {
            right = remaining;
        }
    } else {
        right = remaining;
    }
    
    std::string leftValue = left;
    if (!tableInfo.columns.empty()) {
        bool leftIsColumn = false;
        for (const auto& col : tableInfo.columns) {
            if (col.name == left) {
                leftIsColumn = true;
                break;
            }
        }
        
        if (leftIsColumn) {
            leftValue = ExpressionEvaluator::getColumnValue(left, record, tableInfo);
        }
    }
    
    if (!leftValue.empty() && (leftValue.front() == '"' || leftValue.front() == '\'')) {
        leftValue = leftValue.substr(1, leftValue.size() - 2);
    }
    
    if (!right.empty() && (right.front() == '"' || right.front() == '\'')) {
        right = right.substr(1, right.size() - 2);
    }
    
    return ExpressionEvaluator::compareValues(leftValue, op, right, line, column);
}

bool ExpressionEvaluator::evaluate(const std::string& filter, const std::vector<std::string>& record, const TableInfo& tableInfo) {
    return evaluate(filter, record, tableInfo, 0, 0);
}

std::string ExpressionEvaluator::getColumnValue(const std::string& columnName, const std::vector<std::string>& record, const TableInfo& tableInfo) {
    for (size_t i = 0; i < tableInfo.columns.size(); ++i) {
        if (tableInfo.columns[i].name == columnName) {
            if (i < record.size()) {
                return record[i];
            } else {
                std::cerr << "Error: Record index out of bounds for column '" << columnName << "'" << std::endl;
                return "";
            }
        }
    }
    
    std::cerr << "Error: Column '" << columnName << "' not found in table '" << tableInfo.name << "'" << std::endl;
    return "";
}

bool ExpressionEvaluator::evaluate(const std::string& filter, const std::vector<std::string>& record, const TableInfo& tableInfo, int line, int column) {
    try {
        // 去除首尾空格
        std::string trimmedFilter = filter;
        size_t start = trimmedFilter.find_first_not_of(" ");
        size_t end = trimmedFilter.find_last_not_of(" ");
        if (start != std::string::npos && end != std::string::npos) {
            trimmedFilter = trimmedFilter.substr(start, end - start + 1);
        }
        
        // 处理带括号的情况
        if (!trimmedFilter.empty() && trimmedFilter.front() == '(' && trimmedFilter.back() == ')') {
            trimmedFilter = trimmedFilter.substr(1, trimmedFilter.size() - 2);
            // 再次去除空格
            start = trimmedFilter.find_first_not_of(" ");
            end = trimmedFilter.find_last_not_of(" ");
            if (start != std::string::npos && end != std::string::npos) {
                trimmedFilter = trimmedFilter.substr(start, end - start + 1);
            }
        }
        
        // 检查是否包含AND或OR运算符
        auto [op, pos] = findTopLevelLogicalOperator(trimmedFilter);
        
        if (!op.empty() && pos != std::string::npos) {
            // 分割表达式为左右两部分
            std::string leftExpr = trimmedFilter.substr(0, pos);
            std::string rightExpr = trimmedFilter.substr(pos + op.length() + 1); // +1 是因为有空格
            
            // 递归评估左右两部分
            bool leftResult = evaluate(leftExpr, record, tableInfo, line, column);
            
            // 短路逻辑：如果是AND且左表达式为false，直接返回false；如果是OR且左表达式为true，直接返回true
            if (op == "AND" && !leftResult) return false;
            if (op == "OR" && leftResult) return true;
            
            bool rightResult = evaluate(rightExpr, record, tableInfo, line, column);
            
            // 应用逻辑运算符
            if (op == "AND") {
                return leftResult && rightResult;
            } else if (op == "OR") {
                return leftResult || rightResult;
            }
        }
        
        // 如果没有AND/OR运算符，评估简单表达式
        return evaluateSimpleExpression(trimmedFilter, record, tableInfo, line, column);
    } catch (const std::exception& e) {
        if (line > 0 && column > 0) {
            std::cerr << "Error at line " << line << ", column " << column << ": " << e.what() << std::endl;
        } else {
            std::cerr << "Error evaluating expression: " << e.what() << std::endl;
        }
        return false;
    } catch (...) {
        if (line > 0 && column > 0) {
            std::cerr << "Unknown error at line " << line << ", column " << column << " evaluating expression" << std::endl;
        } else {
            std::cerr << "Unknown error evaluating expression" << std::endl;
        }
        return false;
    }
}

bool ExpressionEvaluator::compareValues(const std::string& left, const std::string& op, const std::string& right, int line, int column) {
    if (op == "=") {
        return left == right;
    } else if (op == "!=" || op == "<>") {
        return left != right;
    }
    
    try {
        int leftInt = std::stoi(left);
        int rightInt = std::stoi(right);
        
        if (op == ">") return leftInt > rightInt;
        if (op == "<") return leftInt < rightInt;
        if (op == ">=") return leftInt >= rightInt;
        if (op == "<=") return leftInt <= rightInt;
    } catch (...) {
        if (op == ">") return left > right;
        if (op == "<") return left < right;
        if (op == ">=") return left >= right;
        if (op == "<=") return left <= right;
    }
    
    if (op == "LIKE") {
        if (right.find('%') != std::string::npos) {
            std::string pattern = right;
            std::replace(pattern.begin(), pattern.end(), '%', '.');
            
            if (pattern.front() == '.' && pattern.back() == '.') {
                std::string subPattern = pattern.substr(1, pattern.size() - 2);
                return left.find(subPattern) != std::string::npos;
            } else if (pattern.front() == '.') {
                std::string subPattern = pattern.substr(1);
                return left.size() >= subPattern.size() && left.substr(left.size() - subPattern.size()) == subPattern;
            } else if (pattern.back() == '.') {
                std::string subPattern = pattern.substr(0, pattern.size() - 1);
                return left.size() >= subPattern.size() && left.substr(0, subPattern.size()) == subPattern;
            }
        } else {
            return left == right;
        }
    }
    
    if (line > 0 && column > 0) {
        std::cerr << "Warning at line " << line << ", column " << column << ": Unsupported operator '" << op << "' in WHERE clause" << std::endl;
    } else {
        std::cerr << "Warning: Unsupported operator '" << op << "' in WHERE clause" << std::endl;
    }
    return false;
}